package com.guotd.ticketSystem.controller;

import com.guotd.ticketSystem.entity.User;
import com.guotd.ticketSystem.mapper.UserMapper;
import com.guotd.ticketSystem.utils.SessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id=request.getParameter("id");
        String password=request.getParameter("password");
        int type= Integer.parseInt(request.getParameter("group1"));
        SqlSession session = SessionUtil.getSqlSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user= userMapper.login(id,password,type);
        if (user==null) {
            request.getSession().setAttribute("user_msg", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
       else if(user.getType()==1){     //普通用户
            request.getSession().setAttribute("user", user);
            request.getSession().setAttribute("type",type);
            response.sendRedirect("index_user.jsp");
        }
        else if(user.getType()==2){  //管理员
            request.getSession().setAttribute("user", user);
            request.getSession().setAttribute("type",type);
            response.sendRedirect("index_admin.jsp");
        }
    }
}
